﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LabChecker.Models;

namespace LabChecker.Controllers
{ 
    [Authorize]
    public class TaskController : Controller
    {
        private LabCheckerContext db = new LabCheckerContext();

        public ViewResult Index(int subjectId)
        {
            var subject = db.Subjects.Find(subjectId);

            ViewBag.SubjectName = subject.Name;
            ViewBag.SubjectId = subject.Id;

            return View(subject.Tasks.OrderBy(t => int.Parse(t.Description.Title.Split(' ')[1])));            
        }

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult Create(Task task)
        {
            if (ModelState.IsValid)
            {
                db.Tasks.Add(task);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(task);
        }
        
        public ActionResult Edit(int id)
        {
            Task task = db.Tasks.Find(id);            
            return View(task);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            var task = db.Tasks.Find(id);

            if (TryUpdateModel(task))
            {
                db.SaveChanges();
                return RedirectToAction("Index", new { subjectId = task.Subject.Id });
            }
            
            return View(task);
        }

        public ActionResult Delete(int id)
        {
            Task task = db.Tasks.Find(id);
            return View(task);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Task task = db.Tasks.Find(id);
            db.Tasks.Remove(task);
            db.SaveChanges();
            return RedirectToAction("Index", new { subjectId = task.Subject.Id });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}